<?php

namespace Kollway\Logger;

use Illuminate\Support\ServiceProvider;

class LoggerServiceProvider extends ServiceProvider
{
    protected $defer = true;

    public function boot()
    {
        $this->publishes([
            __DIR__ . '/migrations' => database_path('migrations')
        ], 'migrations');

        $this->loadViewsFrom(__DIR__ . '/resources/views', 'logger');
    }

    public function register()
    {
        // 添加捕获响应的中间件
        $this->addMiddleware();

        // 添加路由
        $this->addRoute();
    }

    // 前提是测试服务器或本地
    protected function addMiddleware()
    {
        if (str_contains(request()->getHost(), 'kollway.com')
            || str_contains(request()->getHost(), '127.0.0.1')
            || str_contains(request()->getHost(), 'local')) {
            app(\Illuminate\Contracts\Http\Kernel::class)
                ->pushMiddleware(\Kollway\Logger\Middleware\CatchResponseMiddleware::class);
        }
    }

    // 添加查看 log 的路由
    protected function addRoute()
    {
        $this->app['router']->get('_logger', \Kollway\Logger\Controllers\LoggerController::class . '@logger');
        $this->app['router']->get('_clear_log', \Kollway\Logger\Controllers\LoggerController::class . '@clearLog');
    }
}